import json
import smtplib
from .models import *
from . import product_views
from user.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


# 添加追踪商品
@csrf_exempt
def add_trace_product(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        product_name = data.get('product_name')
        platform = data.get('platform')
        user_id = data.get('user_id')
        product_id = data.get('product_id')
        target_price = data.get('target_price')
        filter_trace_product = TraceProduct.objects.filter(
            platform=platform,
            user_id=user_id,
            product_id=product_id,
        )
        if filter_trace_product.exists():
            filter_trace_product = filter_trace_product.first()
            filter_trace_product.target_price = target_price
            filter_trace_product.save()
        else:
            new_trace_product = TraceProduct(
                product_name=product_name,
                platform=platform,
                user_id=user_id,
                product_id=product_id,
                target_price=target_price,
            )
            new_trace_product.save()
        return JsonResponse({"success": "successfully add trace product"}, status=200)
    elif request.method == 'OPTION':
        return JsonResponse({"success": "OPTION operation"}, status=200)
    else:
        return JsonResponse({"error": "Method not allowed"}, status=405)


# 获取当前所有的追踪商品
@csrf_exempt
def get_trace_product(request):
    if request.method == 'GET':
        success_response_dict = {"success": "GET operation"}
        trace_product_list = []
        user_id = request.GET.get('user_id')
        filter_trace_products = TraceProduct.objects.filter(user_id=user_id)
        for trace_product in filter_trace_products:
            trace_product_list.append({
                "platform": trace_product.platform,
                "product_name": trace_product.product_name,
                "target_price": trace_product.target_price,
                "product_id": trace_product.product_id,
                "product_url": product_views.get_product_url_from_id(trace_product.product_id, trace_product.platform),
                "add_date": trace_product.add_date,
            })
        success_response_dict['trace_product_list'] = trace_product_list
        return JsonResponse(success_response_dict, status=200)
    else:
        return JsonResponse({"error": "Method not allowed"}, status=405)


# 修改指定的追踪商品
@csrf_exempt
def modify_trace_product(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        platform = data.get('platform')
        user_id = data.get('user_id')
        product_id = data.get('product_id')
        target_price = data.get('target_price')
        filter_trace_product = TraceProduct.objects.filter(
            platform=platform,
            user_id=user_id,
            product_id=product_id,
        )
        if not filter_trace_product.exists():
            return JsonResponse({'error': 'Trace product not exists'}, status=405)
        else:
            filter_trace_product = filter_trace_product.first()
            filter_trace_product.target_price = target_price
            filter_trace_product.save()
            return JsonResponse({"success": "Modify Trace Product Successful"}, status=200)
    elif request.method == 'OPTION':
        return JsonResponse({"success": "OPTION operation"}, status=200)
    else:
        return JsonResponse({"error": "Method not allowed"}, status=405)


# 删除指定的追踪商品
@csrf_exempt
def delete_trace_product(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        platform = data.get('platform')
        user_id = data.get('user_id')
        product_id = data.get('product_id')
        filter_trace_product = TraceProduct.objects.filter(
            platform=platform,
            user_id=user_id,
            product_id=product_id,
        )
        if not filter_trace_product.exists():
            return JsonResponse({"error": "Product not exists"}, status=405)
        else:
            filter_trace_product = filter_trace_product.first()
            filter_trace_product.delete()
        return JsonResponse({"success": "Trace Product delete successfully"}, status=200)
    elif request.method == 'OPTION':
        return JsonResponse({"success": "OPTION operation"}, status=200)
    else:
        return JsonResponse({"error": "Method not allowed"}, status=405)


# 检查追踪商品
def inspect_trace_products(product_id, price):
    filter_product = Product.objects.filter(product_id=product_id)
    if filter_product.exists():
        product_name = filter_product[0].name
        filter_trace_products = TraceProduct.objects.filter(product_id=product_id)
        # 遍历所有追踪了该商品的用户
        for product in filter_trace_products:
            # 如果价格低于用户预期价格，则向用户发送邮件
            if price <= product.target_price:
                send_message(product.user_id, product_name)
    return None


def send_message(user_id, product_name):
    try:
        # 设置邮件服务器和端口 (以QQ邮箱为例)
        smtp_server = "smtp.qq.com"  # 替换为你的邮件服务商的SMTP服务器
        smtp_port = 465  # SSL端口
        sender_email = "1449035468@qq.com"
        sender_password = "zshxrvtpbowxgeba"
        filter_user = User.objects.filter(id=user_id)
        if filter_user.exists():
            receiver_email = filter_user[0].email
            print(receiver_email)
            subject = "降价提醒"
            body = f"你追踪的 {product_name} 已经降价，请及时查看"

            # 创建邮件内容
            message = MIMEMultipart()
            message["From"] = sender_email
            message["To"] = receiver_email
            message["Subject"] = subject
            # 邮件正文
            message.attach(MIMEText(body, "plain"))  # plain 表示纯文本邮件

            # 连接到SMTP服务器
            server = smtplib.SMTP_SSL(smtp_server, smtp_port)  # 使用SSL加密连接
            server.login(sender_email, sender_password)  # 登录邮箱账号

            # 发送邮件
            server.sendmail(sender_email, receiver_email, message.as_string())
            print("邮件发送成功！")

            # 关闭SMTP服务器连接
            server.quit()
        else:
            print('用户不存在')

    except Exception as e:
        print(f"邮件发送失败: {e}")


# 测试邮件发送功能
@csrf_exempt
def check_user_trace(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        user_id = data.get('user_id')
        product_name = '测试商品'
        send_message(user_id, product_name)
        return JsonResponse({"success": "POST operation"}, status=200)
    elif request.method == 'OPTION':
        return JsonResponse({"success": "OPTION operation"}, status=200)
    else:
        return JsonResponse({"error": "Method not allowed"}, status=405)


@csrf_exempt
def get_history_price(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        platform = data.get('platform')
        product_id = data.get('product_id')
        price_list = []
        date_list = []
        filter_history_product = HistoryProduct.objects.filter(
            platform=platform,
            product_id=product_id,
        ).order_by('add_date')
        for product in filter_history_product:
            price_list.append(product.price)
            date_list.append(product.add_date)
        return JsonResponse({
            'price_list': price_list,
            'date_list': date_list,
        }, status=200)
    elif request.method == 'OPTION':
        return JsonResponse({"success": "OPTION operation"}, status=200)
    else:
        return JsonResponse({"error": "Method not allowed"}, status=405)
